<?php

namespace App\Http\Controllers;

use App\Article;
use Illuminate\Support\Facades\Auth;
use Request;
use Carbon\Carbon;
use App\Http\Requests;
use App\Http\Requests\ArticleRequest;
use App\Http\Controllers\Controller;

class ArticlesController extends Controller
{

    public function __construct() {
        $this->middleware('auth', ['except' => 'index']);  // 'only' => 'create'
    }
    public function index() {

        $articles = Article::latest('published_at')->published()->get();

        return view('articles.index', compact('articles'));

    }

    public function show($article) {

        return view('articles.show', compact('article'));
    }

    public function create() {

        if (Auth::guest()) {
            return redirect('articles');
        }
        return view('articles.create');
    }

    public function store(ArticleRequest $request) {

//        $article = new Article($request->all());
        Auth::user()->articles()->create($request->all());

        session()->flash('flash_message', 'You article has been created!');
        session()->flash('flash_message_important', true);

        return redirect('articles')->with([
            'flash_message' => 'You article has been created!',
            'flash_message_important' => true
        ]);
    }

    public function edit($article) {

        return view('articles.edit', compact('article'));
    }

    public function update($article, ArticleRequest $request) {

        $article->update($request->all());

        return redirect('articles');
    }
}
